import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import '../../models/carbon_footprint_record.dart';
import '../../services/carbon_footprint_service.dart';
import '../../state/auth_provider.dart';
import 'package:provider/provider.dart';

/// 碳足迹记录表单页面
class CarbonFootprintFormScreen extends StatefulWidget {
  final CarbonFootprintRecord? record;

  const CarbonFootprintFormScreen({super.key, this.record});

  @override
  State<CarbonFootprintFormScreen> createState() => _CarbonFootprintFormScreenState();
}

class _CarbonFootprintFormScreenState extends State<CarbonFootprintFormScreen> {
  final Logger _logger = Logger();
  final CarbonFootprintService _carbonFootprintService = CarbonFootprintService();
  final _formKey = GlobalKey<FormState>();

  // 表单控制器
  final _recordNameController = TextEditingController();
  final _productionCapacityController = TextEditingController();
  final _energyConsumptionController = TextEditingController();
  final _carbonEmissionController = TextEditingController();
  final _energySourceController = TextEditingController();
  final _equipmentEfficiencyController = TextEditingController();
  final _operationHoursController = TextEditingController();
  final _locationController = TextEditingController();
  final _projectPhaseController = TextEditingController();
  final _descriptionController = TextEditingController();

  // 表单状态
  bool _isEditMode = false;
  bool _isLoading = false;
  String? _errorMessage;
  DateTime _selectedDate = DateTime.now();
  int _selectedProcessType = 1;
  List<Map<String, dynamic>> _processTypes = [];

  @override
  void initState() {
    super.initState();
    _isEditMode = widget.record != null;
    _loadProcessTypes();
    if (_isEditMode) {
      _loadRecordData();
    }
  }

  @override
  void dispose() {
    _recordNameController.dispose();
    _productionCapacityController.dispose();
    _energyConsumptionController.dispose();
    _carbonEmissionController.dispose();
    _energySourceController.dispose();
    _equipmentEfficiencyController.dispose();
    _operationHoursController.dispose();
    _locationController.dispose();
    _projectPhaseController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  /// 加载工艺类型
  Future<void> _loadProcessTypes() async {
    _logger.d('🔍 开始加载工艺类型');
    
    try {
      final types = await _carbonFootprintService.getProcessTypes();
      setState(() {
        _processTypes = types;
      });
      _logger.i('✅ 工艺类型加载成功: ${types.length} 种工艺');
    } catch (e) {
      _logger.e('❌ 工艺类型加载失败: $e');
      setState(() {
        _errorMessage = '加载工艺类型失败: $e';
      });
    }
  }

  /// 加载记录数据（编辑模式）
  void _loadRecordData() {
    _logger.d('📝 加载记录数据用于编辑');
    
    final record = widget.record!;
    
    _recordNameController.text = record.recordName;
    _productionCapacityController.text = record.productionCapacity.toString();
    _energyConsumptionController.text = record.energyConsumption.toString();
    _carbonEmissionController.text = record.carbonEmission.toString();
    _energySourceController.text = record.energySource ?? '';
    _equipmentEfficiencyController.text = record.equipmentEfficiency?.toString() ?? '';
    _operationHoursController.text = record.operationHours?.toString() ?? '';
    _locationController.text = record.location ?? '';
    _projectPhaseController.text = record.projectPhase ?? '';
    _descriptionController.text = record.description ?? '';
    
    _selectedProcessType = record.processType;
    _selectedDate = record.recordDate;
    
    _logger.i('✅ 记录数据加载完成');
  }

  /// 保存记录
  Future<void> _saveRecord() async {
    _logger.d('💾 开始保存碳足迹记录');
    
    if (!_formKey.currentState!.validate()) {
      _logger.w('⚠️ 表单验证失败');
      return;
    }

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      // 获取当前用户ID
      final authProvider = Provider.of<AuthProvider>(context, listen: false);
      final currentUser = authProvider.currentUser;
      
      if (currentUser == null) {
        throw Exception('用户未登录');
      }

      // 构建记录对象
      final record = CarbonFootprintRecord(
        id: _isEditMode ? widget.record!.id : null,
        recordCode: _isEditMode ? widget.record!.recordCode : '', // 新增时由服务生成
        recordName: _recordNameController.text.trim(),
        processType: _selectedProcessType,
        productionCapacity: double.parse(_productionCapacityController.text),
        energyConsumption: double.parse(_energyConsumptionController.text),
        carbonEmission: double.parse(_carbonEmissionController.text),
        energySource: _energySourceController.text.trim().isEmpty ? null : _energySourceController.text.trim(),
        equipmentEfficiency: _equipmentEfficiencyController.text.trim().isEmpty 
            ? null 
            : double.parse(_equipmentEfficiencyController.text),
        operationHours: _operationHoursController.text.trim().isEmpty 
            ? null 
            : int.parse(_operationHoursController.text),
        location: _locationController.text.trim().isEmpty ? null : _locationController.text.trim(),
        projectPhase: _projectPhaseController.text.trim().isEmpty ? null : _projectPhaseController.text.trim(),
        recordDate: _selectedDate,
        description: _descriptionController.text.trim().isEmpty ? null : _descriptionController.text.trim(),
        createdBy: currentUser.id!,
        createdAt: _isEditMode ? widget.record!.createdAt : DateTime.now(),
        updatedAt: DateTime.now(),
        isDeleted: false,
      );

      // 验证数据
      final errors = CarbonFootprintService.validateRecordData(
        recordName: record.recordName,
        processType: record.processType,
        productionCapacity: record.productionCapacity,
        energyConsumption: record.energyConsumption,
        carbonEmission: record.carbonEmission,
        energySource: record.energySource,
        equipmentEfficiency: record.equipmentEfficiency,
        operationHours: record.operationHours,
        location: record.location,
        projectPhase: record.projectPhase,
      );

      // 检查是否有验证错误
      final hasErrors = errors.values.any((error) => error != null);
      if (hasErrors) {
        _logger.w('⚠️ 数据验证失败');
        setState(() {
          _isLoading = false;
          _errorMessage = '请检查输入数据';
        });
        return;
      }

      // 保存记录
      if (_isEditMode) {
        final success = await _carbonFootprintService.updateRecord(record);
        if (success) {
          _logger.i('✅ 碳足迹记录更新成功');
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('记录更新成功')),
          );
          Navigator.of(context).pop();
        } else {
          _logger.w('⚠️ 碳足迹记录更新失败');
          setState(() {
            _isLoading = false;
            _errorMessage = '更新失败，请重试';
          });
        }
      } else {
        final createdRecord = await _carbonFootprintService.createRecord(record);
        _logger.i('✅ 碳足迹记录创建成功: ${createdRecord.recordName}');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('记录"${createdRecord.recordName}"创建成功')),
        );
        Navigator.of(context).pop();
      }
    } catch (e) {
      _logger.e('❌ 保存碳足迹记录失败: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '保存失败: $e';
      });
    }
  }

  /// 构建表单字段
  Widget _buildFormField({
    required String label,
    required TextEditingController controller,
    required String? Function(String?) validator,
    TextInputType? keyboardType,
    String? hintText,
    int? maxLines,
    bool enabled = true,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: TextFormField(
        controller: controller,
        validator: validator,
        keyboardType: keyboardType,
        maxLines: maxLines ?? 1,
        enabled: enabled && !_isLoading,
        decoration: InputDecoration(
          labelText: label,
          hintText: hintText,
          border: const OutlineInputBorder(),
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑记录' : '新增记录'),
        actions: [
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(16),
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              if (_errorMessage != null)
                Container(
                  padding: const EdgeInsets.all(12),
                  margin: const EdgeInsets.only(bottom: 16),
                  decoration: BoxDecoration(
                    color: Colors.red.shade50,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.red.shade200),
                  ),
                  child: Text(
                    _errorMessage!,
                    style: TextStyle(color: Colors.red.shade700),
                  ),
                ),
              
              // 记录名称
              _buildFormField(
                label: '记录名称 *',
                controller: _recordNameController,
                validator: CarbonFootprintRecord.validateRecordName,
                hintText: '请输入记录名称',
              ),
              
              // 工艺类型
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: DropdownButtonFormField<int>(
                  decoration: const InputDecoration(
                    labelText: '工艺类型 *',
                    border: OutlineInputBorder(),
                    contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                  value: _selectedProcessType,
                  items: _processTypes.map((type) => DropdownMenuItem(
                    value: type['id'] as int,
                    child: Text(type['type_name'] as String),
                  )).toList(),
                  onChanged: _isLoading ? null : (value) {
                    setState(() {
                      _selectedProcessType = value!;
                    });
                  },
                  validator: CarbonFootprintRecord.validateProcessType,
                ),
              ),
              
              // 产能
              _buildFormField(
                label: '产能 (吨/年) *',
                controller: _productionCapacityController,
                validator: CarbonFootprintRecord.validateProductionCapacity,
                keyboardType: TextInputType.number,
                hintText: '请输入产能',
              ),
              
              // 能耗
              _buildFormField(
                label: '能耗 (kWh/吨) *',
                controller: _energyConsumptionController,
                validator: CarbonFootprintRecord.validateEnergyConsumption,
                keyboardType: TextInputType.number,
                hintText: '请输入能耗',
              ),
              
              // 碳排放量
              _buildFormField(
                label: '碳排放量 (吨CO2/吨) *',
                controller: _carbonEmissionController,
                validator: CarbonFootprintRecord.validateCarbonEmission,
                keyboardType: TextInputType.number,
                hintText: '请输入碳排放量',
              ),
              
              // 能源来源
              _buildFormField(
                label: '能源来源',
                controller: _energySourceController,
                validator: (value) => null, // 可选字段
                hintText: '请输入能源来源',
              ),
              
              // 设备效率
              _buildFormField(
                label: '设备效率 (%)',
                controller: _equipmentEfficiencyController,
                validator: CarbonFootprintRecord.validateEquipmentEfficiency,
                keyboardType: TextInputType.number,
                hintText: '请输入设备效率 (0-100)',
              ),
              
              // 运行时间
              _buildFormField(
                label: '运行时间 (小时)',
                controller: _operationHoursController,
                validator: CarbonFootprintRecord.validateOperationHours,
                keyboardType: TextInputType.number,
                hintText: '请输入年运行时间 (0-8760)',
              ),
              
              // 地理位置
              _buildFormField(
                label: '地理位置',
                controller: _locationController,
                validator: CarbonFootprintRecord.validateLocation,
                hintText: '请输入地理位置',
              ),
              
              // 项目阶段
              _buildFormField(
                label: '项目阶段',
                controller: _projectPhaseController,
                validator: CarbonFootprintRecord.validateProjectPhase,
                hintText: '请输入项目阶段',
              ),
              
              // 记录日期
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: TextFormField(
                  decoration: const InputDecoration(
                    labelText: '记录日期 *',
                    border: OutlineInputBorder(),
                    contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                  readOnly: true,
                  controller: TextEditingController(
                    text: _selectedDate.toString().split(' ')[0],
                  ),
                  onTap: _isLoading ? null : () async {
                    final date = await showDatePicker(
                      context: context,
                      initialDate: _selectedDate,
                      firstDate: DateTime(2020),
                      lastDate: DateTime.now(),
                    );
                    if (date != null) {
                      setState(() {
                        _selectedDate = date;
                      });
                    }
                  },
                ),
              ),
              
              // 详细描述
              _buildFormField(
                label: '详细描述',
                controller: _descriptionController,
                validator: (value) => null, // 可选字段
                hintText: '请输入详细描述',
                maxLines: 3,
              ),
              
              const SizedBox(height: 32),
              
              // 操作按钮
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: _isLoading ? null : _saveRecord,
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      child: Text(_isEditMode ? '更新记录' : '保存记录'),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: OutlinedButton(
                      onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                      style: OutlinedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      child: const Text('取消'),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
} 